/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import com.openbrew.openbrewrf.DiscountCode;
import com.openbrew.openbrewrf.InvPSOLines;
import com.openbrew.openbrewrf.PSOLines;
import com.openbrew.openbrewrf.PendingSO;
import java.util.List;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import tools.InventoryModifiers;
import tools.PendingSOTools;
import tools.SaleTools;
import tools.model.PSOFullfillment;

/**
 *
 * @author chapmand
 */
@Stateless
@Path("com.openbrew.openbrewrf.pendingso")
public class PendingSOFacadeREST extends AbstractFacade<PendingSO> {
    @PersistenceContext(unitName = "com.openBrew_openBrewRF_war_1.0PU")
    private EntityManager em;

    public PendingSOFacadeREST() {
        super(PendingSO.class);
    }

    @POST
    @Override
    @WebMethod(operationName = "create")
    @Consumes({"application/xml", "application/json"})
    public PendingSO create(@WebParam(name = "pendingso") PendingSO entity) {
        final InventoryModifiers im = new InventoryModifiers();
        if(entity.getPSOLinesCollection()!=null){
            for(PSOLines psoLine : entity.getPSOLinesCollection()){
                if(psoLine.getPSOID() == null || psoLine.getPSOID() == 0){
                    im.doFGIAllocationAddition(em, psoLine.getPSOFGI().getFgiid()
                            , psoLine.getPSOQty());
                }
            }
        }
        if(entity.getInvPSOLinesCollection()!=null){
            for(InvPSOLines psoLine : entity.getInvPSOLinesCollection()){
                if(psoLine.getInvPSOID() == null || psoLine.getInvPSOID() == 0){
                    im.doSupplyAllocationAddition(em, psoLine.getInvPSOSupplyID().getSupID()
                            , psoLine.getInvPSOQty());
                }
            }
        }
        entity = super.create(entity);
        return entity;
    }

    @PUT
    @Override
    @Consumes({"application/xml", "application/json"})
    public void edit(PendingSO entity) {
        final SaleTools st = new SaleTools();
        final DiscountCode noDiscount = getNoDiscount(em);
        st.fgiAllocationUpdatePerPSO(em, entity);
        st.supplyAllocationUpdatePerPSO(em, entity);
        if(entity.getPSOLinesCollection()!=null){
            for(PSOLines pso : entity.getPSOLinesCollection()){
                if(pso.getPSODiscCode() == null){
                    pso.setPSODiscCode(noDiscount);
                }
            }
        }
        if(entity.getInvPSOLinesCollection()!=null){
            for(InvPSOLines pso : entity.getInvPSOLinesCollection()){
                if(pso.getInvPSOdisc() == null){
                    pso.setInvPSOdisc(noDiscount);
                }
            }
        }
        super.edit(entity);
    }
    
    private DiscountCode getNoDiscount(final EntityManager en){
        TypedQuery<DiscountCode> query = en.createQuery(
            "SELECT d FROM DiscountCode d WHERE d.discID='1'", DiscountCode.class);
        return query.getSingleResult();
    }

    @DELETE
    @Path("{id}")
    public void remove(@PathParam("id") Integer id) {
        super.remove(super.find(id));
    }

    @GET
    @Path("{id}")
    @Produces({"application/xml", "application/json"})
    public PendingSO find(@PathParam("id") Integer id) {
        return super.find(id);
    }

    @GET
    @Override
    @Produces({"application/xml", "application/json"})
    public List<PendingSO> findAll() {
        return super.findAll();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({"application/xml", "application/json"})
    public List<PendingSO> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        return super.findRange(new int[]{from, to});
    }

    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }
    
    @GET
    @Path("runNamedQueryWithID/{str}/{id}")
    @Override
    @Produces({"application/xml", "application/json"})
    public List<PendingSO> runNamedQueryWithID(@PathParam("str") String str
            , @PathParam("id") int id){
        return super.runNamedQueryWithID(str, id);
    }
    
    @GET
    @Path("runNamedQuery/{str}")
    @Override
    @Produces({"application/xml", "application/json"})
    public List<PendingSO> runNamedQuery(@PathParam("str") String str){
        return super.runNamedQuery(str);
    }

    @PUT
    @Path("fullfillPartial")
    @Consumes({"application/xml", "application/json"})
    @Produces(MediaType.APPLICATION_XML)
    public PSOFullfillment fullfillPartial(PendingSO entity) {
        final PendingSO curpso = getPSOFromID(em, entity.getPSOAllocationID());
        //if(entity.getVersion() == curpso.getVersion()){
            final PendingSOTools psot = new PendingSOTools();
            return psot.doPartialFullfillment(em, entity);
        //} 
        //return null;
    }

    @PUT
    @Path("fullfillWhole")
    @Consumes({"application/xml", "application/json"})
    @Produces(MediaType.APPLICATION_XML)
    public PSOFullfillment fullfillWhole(PendingSO entity) {
        final PendingSO curpso = getPSOFromID(em, entity.getPSOAllocationID());
        //if(entity.getVersion() == curpso.getVersion()){
            final PendingSOTools psot = new PendingSOTools();
            return psot.doFullFullfillment(em, entity);
        //}
        //return null;
    }
    
    private PendingSO getPSOFromID(final EntityManager en, final int psoID){
        TypedQuery<PendingSO> query = en.createQuery(
                "SELECT p FROM PendingSO p WHERE p.psoid = ?1", PendingSO.class);
        query.setParameter(1, psoID);
        PendingSO pso = query.getSingleResult();
        return pso;
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    
}
